package com.rency.mtds.starter.client.provider;

import com.alibaba.druid.pool.DruidDataSource;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author: caiyu.ren
 * Created on 2019/9/3 9:28
 * @version: V1.0.0
 * @since JDK 11
 */
@Slf4j
public abstract class AbstractDataSourceRouteProvider implements DataSourceRouteProvider{

    protected DataSource createDataSource(DataSourceProperties properties) {
        Class<? extends DataSource> type = properties.getType();
        if (type == null) {
            try {
                Class.forName("com.alibaba.druid.pool.DruidDataSource");
                return createDruidDataSource(properties);
            } catch (ClassNotFoundException e) {
                log.debug("dynamic not found DruidDataSource");
            }
            try {
                Class.forName("com.zaxxer.hikari.HikariDataSource");
                return createHikariDataSource(properties);
            } catch (ClassNotFoundException e) {
                log.debug("dynamic not found HikariDataSource");
            }
            throw new RuntimeException("please set master and slave type like spring.dynamic.datasource.master.type");
        } else {
            if ("com.alibaba.druid.pool.DruidDataSource".equals(type.getName())) {
                return createDruidDataSource(properties);
            } else {
                return properties.initializeDataSourceBuilder().build();
            }
        }
    }

    private DataSource createHikariDataSource(DataSourceProperties properties) {
        properties.setType(HikariDataSource.class);
        return properties.initializeDataSourceBuilder().build();
    }

    private DataSource createDruidDataSource(DataSourceProperties properties) {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(properties.getUrl());
        druidDataSource.setUsername(properties.getUsername());
        druidDataSource.setPassword(properties.getPassword());
        druidDataSource.setDriverClassName(properties.getDriverClassName());
        try {
            druidDataSource.setFilters("stat,wall");
            druidDataSource.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return druidDataSource;
    }
}
